package com.lemon.smartsafetynew.ui.activity.patrol;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectNoSwipeBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.common.EnterTypeEnum;
import com.lemon.smartsafetynew.entity.common.NetResultBo;
import com.lemon.smartsafetynew.entity.contact.PersonVo;
import com.lemon.smartsafetynew.entity.event.contact.PersonEvent;
import com.lemon.smartsafetynew.entity.event.patrol.ChildItemEvent;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemConclusionVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemResultBo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolCheckItemVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolChildItemDetailHistoryVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolChildItemHistoryVo;
import com.lemon.smartsafetynew.entity.patrol.SafePatrolMediaVo;
import com.lemon.smartsafetynew.net.services.SafePatrolServices;
import com.lemon.smartsafetynew.ui.activity.contact.GovGridLeaderListActivity;
import com.lemon.smartsafetynew.ui.activity.contact.PersonListActivity;
import com.lemon.smartsafetynew.ui.adapter.patrol.PatrolAttachmentAdapter;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.TimeFormatConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * 描述：本页面会有两种类型的进入
 * 1. 当点击检查项的子项
 * 2. 当点击历史巡查后的检查项的历史子项记录
 * <p>
 * Created by Andrew on 2017/8/2.
 */

public class SafePatrolCheckItemDetailActivity extends PhotoSelectNoSwipeBaseActivity
        implements RecyclerTClickListener<SafePatrolMediaVo> {

    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;

    @Bind(R.id.check_item_name)
    TextView checkItemName;
    @Bind(R.id.check_explain_tv)
    TextView checkExplainTv;
    @Bind(R.id.last_check_result_label)
    TextView lastCheckResultLabel;
    @Bind(R.id.last_check_result_status)
    ImageView lastCheckResultStatus;
    @Bind(R.id.last_check_result_tv)
    TextView lastCheckResultTv;
    @Bind(R.id.last_check_result_layout)
    LinearLayout lastCheckResultLayout;
    @Bind(R.id.now_check_result_status)
    ImageView nowCheckResultStatus;
    @Bind(R.id.now_check_result_tv)
    TextView nowCheckResultTv;
    @Bind(R.id.success_radio_btn)
    RadioButton successRadioBtn;
    @Bind(R.id.fail_radio_btn)
    RadioButton failRadioBtn;
    @Bind(R.id.radio_ground_layout)
    LinearLayout radioGroundLayout;
    @Bind(R.id.check_result_remark_tv)
    TextView checkResultRemarkTv;
    @Bind(R.id.check_result_remark_et)
    MaterialEditText checkResultRemarkEt;
    @Bind(R.id.remark_layout)
    LinearLayout remarkLayout;
    @Bind(R.id.attachment_tv)
    TextView attachmentTv;
    @Bind(R.id.mSelectRecycleView)
    RecyclerView mSelectRecycleView;
    @Bind(R.id.mLoadRecycleView)
    RecyclerView mLoadRecycleView;
    @Bind(R.id.check_item_submit_btn)
    Button checkItemSubmitBtn;

    // ===== 整改 ======
    @Bind(R.id.department_tv)
    TextView departmentTv;
    @Bind(R.id.department_arrow_imageView)
    ImageView departmentArrowImageView;
    @Bind(R.id.department_layout)
    LinearLayout departmentLayout;
    @Bind(R.id.responsible_tv)
    TextView responsibleTv;
    @Bind(R.id.responsible_arrow_imageView)
    ImageView responsibleArrowImageView;
    @Bind(R.id.responsible_layout)
    LinearLayout responsibleLayout;
    @Bind(R.id.expect_finish_date_tv)
    TextView expectFinishDateTv;
    @Bind(R.id.expect_finish_date_arrow_imageView)
    ImageView expectFinishDateArrowImageView;
    @Bind(R.id.expect_finish_date_layout)
    LinearLayout expectFinishDateLayout;
    @Bind(R.id.expect_money_et)
    EditText expectMoneyEt;
    @Bind(R.id.expect_money_tv)
    TextView expectMoneyTv;
    @Bind(R.id.rectify_layout)
    LinearLayout rectifyLayout;

    @Bind(R.id.review_person_tv)
    TextView reviewPersonTv;
    @Bind(R.id.review_person_layout)
    LinearLayout reviewPersonLayout;
    @Bind(R.id.review_layout)
    LinearLayout reviewLayout;

    /**
     * 当前检查页进来的 bundle
     */
    private static int task_id;
    private static int position;
    private static String check_id;
    private static SafePatrolCheckItemVo checkItemVo;
    private static SafePatrolCheckItemResultBo checkItemResultBo;
    private static String company_id;
    private static String taskId;
    /**
     * 查看历史检查页进来的 bundle
     */
    private static SafePatrolChildItemDetailHistoryVo childItemDetailHistoryVo;
    private static String item_id;

    /**
     * 公用的判断条件
     */
    private static EnterTypeEnum enterTypeEnum;

    /**
     * 整改人员
     */
    private PersonVo personVo = null;

    /**
     * 复查人员
     */
    private PersonVo reviewPersonVo = null;

    /**
     * UI 变量
     */
    private PatrolAttachmentAdapter mMediaAdapter;
    private List<SafePatrolMediaVo> mMediaVoList = new ArrayList<>();

    /**
     * 每次提交隐患的唯一ID
     */
    private String UUID = "";

    private void initToolbar() {

        toolbar.setTitle("");
        mainTitle.setText("检查详情");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callFinish();
            }
        });

    }

    protected void callFinish() {

        if (failRadioBtn.isChecked() && enterTypeEnum == EnterTypeEnum.NOW) { //当显示检查详情而不是显示历史详情且检查项不通过时，需要提醒用户，提交检查项从而生成隐患。
            showDialog("由于本检查项未通过，请填写整改信息，然后点击页面底部\"创建隐患\"按钮。");
        } else {
            finishActivity();
        }
    }


    private void finishActivity() {
        IApplication._tempOneActivity = null;
        AppManager.getAppManager().finishActivity(SafePatrolCheckItemDetailActivity.this);
        System.gc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_patrol_check_item_detail;
    }

    @Override
    protected void getBundleArgs() {

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {

            enterTypeEnum = (EnterTypeEnum) bundle.getSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_ENTER_TYPE);
            taskId = bundle.getString(KeyConstants.KEY_SAFE_PATROL_TASK_ID_NEW);
            if (enterTypeEnum == EnterTypeEnum.NOW) {
                check_id = bundle.getString(KeyConstants.KEY_SAFE_PATROL_CHECK_ID);
                task_id = bundle.getInt(KeyConstants.KEY_SAFE_PATROL_TASK_ID);
                position = bundle.getInt(KeyConstants.KEY_SAFE_PATROL_POSITION);
                checkItemResultBo = (SafePatrolCheckItemResultBo) bundle.getSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM_BO);
                checkItemVo = (SafePatrolCheckItemVo) bundle.getSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_CHILD_ITEM);
                company_id = bundle.getString(KeyConstants.KEY_COMPANY_ID);
            } else if (enterTypeEnum == EnterTypeEnum.HISTORY) {
                childItemDetailHistoryVo = (SafePatrolChildItemDetailHistoryVo) bundle.getSerializable(KeyConstants.KEY_SAFE_PATROL_CHECK_ITEM_DETAIL_RESULT);
                item_id = bundle.getString(KeyConstants.KEY_SAFE_PATROL_ITEM_ID);
            }
        } else {
            finishActivity();
        }
    }

    @Override
    protected void initViews() {
        super.initViews();

        initToolbar();

        if (enterTypeEnum == EnterTypeEnum.NOW) {
            UUID = CommonUtil.getUUID();
            checkDetailView();  //查看当前记录，并可以修改，可以提交
        } else {
            watchDetailView();  //查看历史记录，不可以修改，不可以提交
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        // ================ 当前检查项上传结果 =============
        if (KeyConstants.URL_SUBMIT_SAFE_PATROL_CHILD_ITEM_RESULT.equals(event.getTag())) { //提交检查子项结果
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                //mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                checkItemSubmitBtn.setEnabled(true);
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            finishActivity();
                        }
                    });

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    if (event.getCode() == NetResultBo.Code.REPEAT_SUBMIT.getCode()) {
                        //此处为过滤重复提交的错误，此错误不需要做任何提示

                    } else {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }

                }
            }
        } else if (KeyConstants.URL_GET_SAFE_PATROL_CHILD_ITEM_HISTORY_LIST.equals(event.getTag())) { //获得检查项结果

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    SafePatrolChildItemHistoryVo childItemHistoryVo = (SafePatrolChildItemHistoryVo) (event.getObj());

                    if (childItemHistoryVo.getAttests() != null && childItemHistoryVo.getAttests().size() != 0) {

                        List<SafePatrolMediaVo> list = new ArrayList<>();

                        for (SafePatrolMediaVo mediaVo : childItemHistoryVo.getAttests()) {
                            if (childItemDetailHistoryVo.getFlow_id().equals(mediaVo.getFlow_id()) && mediaVo.getData_url() != null) {
                                list.add(mediaVo);
                            }
                        }

                        if (mMediaAdapter != null) {
                            mMediaVoList.clear();
                            mMediaAdapter.notifyDataSetChanged();
                            mMediaAdapter.addItems(list);
                        }
                    }


                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            finishActivity();
                        }
                    });
                }
            }

        }

    }


    /**
     * 浏览历史详情页面初始化布局
     */
    private void watchDetailView() {

        lastCheckResultLayout.setVisibility(View.GONE);
        remarkLayout.setVisibility(View.GONE);
        radioGroundLayout.setVisibility(View.GONE);
        mSelectRecycleView.setVisibility(View.GONE);
        checkItemSubmitBtn.setVisibility(View.GONE);
        rectifyLayout.setVisibility(View.GONE);

        checkItemName.setText(childItemDetailHistoryVo.getFlow_name());
        checkExplainTv.setText(childItemDetailHistoryVo.getCheck_way());

        nowCheckResultStatus.setVisibility(View.VISIBLE);
        nowCheckResultTv.setVisibility(View.VISIBLE);

        if ("green_mark".equals(childItemDetailHistoryVo.getMark_code())) {
            nowCheckResultStatus.setImageResource(R.mipmap.icon_check_pass);
            nowCheckResultTv.setTextColor(Color.parseColor("#60CC86"));
            nowCheckResultTv.setText(childItemDetailHistoryVo.getConclusion_name());
        } else {
            nowCheckResultStatus.setImageResource(R.mipmap.icon_check_not_pass);
            nowCheckResultTv.setTextColor(Color.parseColor("#EA654F"));
            nowCheckResultTv.setText(childItemDetailHistoryVo.getConclusion_name());
        }

        checkResultRemarkTv.setText(CommonUtil.avoidNullString(childItemDetailHistoryVo.getRemark()));
        attachmentTv.setText("附件");


        // ==================== RecyclerView ================
        GridLayoutManager gridLayoutManager = new GridLayoutManager(SafePatrolCheckItemDetailActivity.this, 3);
        mLoadRecycleView.setVisibility(View.VISIBLE);
        mLoadRecycleView.setLayoutManager(gridLayoutManager);
        mMediaAdapter = new PatrolAttachmentAdapter(mMediaVoList, this);
        mLoadRecycleView.setAdapter(mMediaAdapter);


        // ===== call Net Data =====
        callHistoryChildItem();
    }


    /**
     * 浏览检查详情页面初始化布局
     */
    private void checkDetailView() {

        checkItemName.setText(checkItemVo.getFlow_name());
        checkExplainTv.setText(checkItemVo.getCheck_way());

        /**
         * 政府人员转交隐患显示的页面
         */
        if (UserTypeUtil.isGovType(AccountUtil.getUserType())) {
            reviewLayout.setVisibility(View.VISIBLE);
        }


        // TODO ==== 现在这个通过Mark_code 比对出结果的方法实在是太糟糕了 =====

        // ========== 上次检查结论 ==========
        Log.e("CheckItemDetail", "checkItemVo.getStatus() = " + checkItemVo.getStatus());
        if (null != checkItemVo.getStatus()) {

            if (CommonUtil.stringEqualsForBigInteger("1", checkItemVo.getStatus())) { //TODO  现在的状态是1是，符合

                lastCheckResultLabel.setTextColor(Color.parseColor("#60CC86"));
                lastCheckResultStatus.setImageResource(R.mipmap.icon_check_pass);

                for (SafePatrolCheckItemConclusionVo safePatrolCheckItemConclusionVo : checkItemVo.getConclusions()) {
                    if ("green_mark".equals(safePatrolCheckItemConclusionVo.getMark_code())) {//green_mark 是符合的关键字
                        lastCheckResultTv.setTextColor(Color.parseColor("#60CC86"));
                        lastCheckResultTv.setText(safePatrolCheckItemConclusionVo.getConclusion_name());
                        break;
                    }
                }

            } else {

                lastCheckResultLabel.setTextColor(Color.parseColor("#EA654F"));
                lastCheckResultStatus.setImageResource(R.mipmap.icon_check_not_pass);

                for (SafePatrolCheckItemConclusionVo safePatrolCheckItemConclusionVo : checkItemVo.getConclusions()) {
                    if ("red_mark".equals(safePatrolCheckItemConclusionVo.getMark_code())) {
                        lastCheckResultTv.setTextColor(Color.parseColor("#EA654F"));
                        lastCheckResultTv.setText(safePatrolCheckItemConclusionVo.getConclusion_name());
                        break;
                    }
                }
            }

        } else {
            lastCheckResultLabel.setTextColor(Color.parseColor("#448AD0"));
            lastCheckResultStatus.setVisibility(View.GONE);
            lastCheckResultTv.setTextColor(Color.parseColor("#605C5B"));
            lastCheckResultTv.setText("无");
        }


        // ======== 本次检查结论 ============
        String[] idList = checkItemResultBo.getFlow_id_conclusion_id().split(",");
        List<SafePatrolCheckItemConclusionVo> list = checkItemVo.getConclusions();

        for (SafePatrolCheckItemConclusionVo checkItemConclusionVo : list) {

            if ("green_mark".equals(checkItemConclusionVo.getMark_code())) {
                successRadioBtn.setText(checkItemConclusionVo.getConclusion_name());
                successRadioBtn.setTag(checkItemConclusionVo.getFlow_id() + "," + checkItemConclusionVo.getConclusion_id());
            } else {
                failRadioBtn.setText(checkItemConclusionVo.getConclusion_name());
                failRadioBtn.setTag(checkItemConclusionVo.getFlow_id() + "," + checkItemConclusionVo.getConclusion_id());
            }
        }

        for (SafePatrolCheckItemConclusionVo checkItemConclusionVo : list) {

            if (checkItemResultBo.isUserChoose()) {
                if (idList[1].equals(checkItemConclusionVo.getConclusion_id())) {
                    if ("green_mark".equals(checkItemConclusionVo.getMark_code())) {
                        successRadioBtn.setChecked(true);
                        checkItemSubmitBtn.setText("提 交");
                        rectifyLayout.setVisibility(View.GONE);    //检查项通过不需要填写整改项
                        break;
                    } else {
                        failRadioBtn.setChecked(true);
                        checkItemSubmitBtn.setText("创建隐患");
                        rectifyLayout.setVisibility(View.VISIBLE); //检查项不通过需要填写整改项
                        break;
                    }
                }
            }
        }

        failRadioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkItemResultBo.setUserChoose(true);
                checkItemResultBo.setFlow_id_conclusion_id((String) v.getTag());
                checkItemResultBo.setStatus(2);            //2 不通过
                rectifyLayout.setVisibility(View.VISIBLE); //检查项不通过需要填写整改项
                checkItemSubmitBtn.setText("创建隐患");
            }
        });

        successRadioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkItemResultBo.setUserChoose(true);
                checkItemResultBo.setFlow_id_conclusion_id((String) v.getTag());
                checkItemResultBo.setStatus(1);            //1 通过
                rectifyLayout.setVisibility(View.GONE);    //检查项通过不需要填写整改项
                checkItemSubmitBtn.setText("提 交");
            }
        });

        responsibleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPersonList();
            }
        });

        expectFinishDateLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickFinishDate();
            }
        });

        reviewPersonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showReviewPersonList();
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (enterTypeEnum == EnterTypeEnum.NOW) {
            AppService.getBus().post(new ChildItemEvent(checkItemResultBo, position));
        }
    }

    @OnClick(R.id.check_item_submit_btn)
    public void onViewClicked() {
        checkItemSubmitBtn.setEnabled(false);
        doSubmit();
    }

    private void doSubmit() {

        mHUDUtil.showHUD();

        if (!checkItemResultBo.isUserChoose()) {
            mHUDUtil.showErrorTip("请选择该检查项本次巡查结果。");
            checkItemSubmitBtn.setEnabled(true);
            return;
        }

        String flow_id_conclusion_id = checkItemResultBo.getFlow_id_conclusion_id();
        String[] array = flow_id_conclusion_id.split(",");

        final LemonRequestParams params = new LemonRequestParams("");

        //params.put("task_id", task_id);
        params.put("check_uuid", UUID);
        params.put("item_id", checkItemVo.getItem_id());
        params.put("taskId",taskId);
        params.put("check_id", check_id);
        params.put("flow_id", array[0]);
        params.put("conclusion_id", array[1]);
        params.put("remark", checkResultRemarkEt.getText().toString().trim());
        //params.put("mobile_type", "Android");

        if (failRadioBtn.isChecked()) { //检查项未通过
            if (verifyParam()) {//表单验证通过
                params.put("rectify_user_id", personVo.getUser_id());
                params.put("rectify_date", expectFinishDateTv.getText().toString().trim());
                //params.put("rectify_money", expectMoneyEt.getText().toString().trim()); 【常熟项目】 没有预计整改金额
                params.put("company_id", company_id);
                if (reviewPersonVo != null) {
                    /**
                     * 当转交复查人对象不为null时，提交 转交复查人员的user_id
                     */
                    params.put("review_user_id", reviewPersonVo.getUser_id());
                } else {
                    /**
                     * 当转交复查人对象为null时，提交当前用户的user_id
                     */
                    params.put("review_user_id", AccountUtil.getUserID());
                }
            } else {          //表单验证失败
                checkItemSubmitBtn.setEnabled(true);
                return;
            }
        }

        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                getUploadMediaItems(new SelectEvidenceAdapter.CropCallBack<Map<String, File>>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFinish(Map<String, File> data) {

                        if (data == null || data.isEmpty()) {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    checkItemSubmitBtn.setEnabled(true);
                                    mHUDUtil.showErrorTip("提交操作必须添加附件。");
                                }
                            });

                        } else {
                            SafePatrolServices
                                    .init()
                                    .submitSafePatrolChildItemResult(params, data);
                        }
                    }
                });
            }
        });


//        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onFinish(List<UploadFileItem> data) {
//
//
//                if (failRadioBtn.isChecked()) {
//
//                    /**
//                     * 检查项未通过
//                     */
//
//                    if (data != null && data.size() != 0) {
//
//                        params.put("files", mGson.toJson(data));
//
//                        new Handler().post(new Runnable() {
//                            @Override
//                            public void run() {
//
//                                SafePatrolServices
//                                        .init()
//                                        .submitSafePatrolChildItemResult(params);
//
//                            }
//                        });
//
//                    } else {
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                mHUDUtil.showErrorTip("当检查结论为检查项不通过时必须添加附件。");
//                            }
//                        });
//
//                    }
//
//                } else {
//
//                    /**
//                     * 检查项通过
//                     */
//
//                    if (data != null && data.size() != 0) {
//                        params.put("files", mGson.toJson(data));
//                    } else {
//                        params.put("files", "");
//                    }
//
//                    new Handler().post(new Runnable() {
//                        @Override
//                        public void run() {
//
//                            SafePatrolServices
//                                    .init()
//                                    .submitSafePatrolChildItemResult(params);
//
//                        }
//                    });
//
//                }
//
//            }
//
//        });

    }

    private void callHistoryChildItem() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("check_id", childItemDetailHistoryVo.getCheck_id());

        SafePatrolServices.init().getSafePatrolChildItemHistoryList(params);
    }

    @Override
    public void onItemClick(SafePatrolMediaVo data, int position) {
        if (LemonFileHelper.isImageUrl(data.getData_url())) {
            List<SafePatrolMediaVo> mediaVos = mMediaAdapter.getData();
            List<PhotoInfo> photos = new ArrayList<>();

            int j = 0;
            int currentItem = 0;
            for (int i = 0; i < mediaVos.size(); i++) {
                if (LemonFileHelper.isImageUrl(mediaVos.get(i).getData_url())) {

                    if (data.getData_url().equals(mediaVos.get(i).getData_url())) {
                        currentItem = j;
                    }

                    PhotoInfo photoInfo = new PhotoInfo();
                    photoInfo.setPhotoId(j);
                    photoInfo.setPhotoPath(HttpUtils.formatFilesUrl(mediaVos.get(i).getData_url()));
                    photos.add(photoInfo);
                    j++;
                }
            }

            if (photos != null && photos.size() != 0) {
                UIHelper.showPhotoView(this, photos, currentItem);
            }
        } else if (LemonFileHelper.isVoiceUrl(data.getData_url())) {
            playVoice(HttpUtils.formatFilesUrl(data.getData_url()));
        }
    }

    /**
     * 提交隐患查报时，验证参数是否完整
     */
    private boolean verifyParam() {


        /**
         * 备注
         */
        if (StringUtils.isEmpty(checkResultRemarkEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写备注说明。");
            return false;
        }

        /**
         * 责任人
         */
        if (StringUtils.isEmpty(responsibleTv.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择责任人。");
            return false;
        }

        /**
         * 预计完成时间
         */
        if (StringUtils.isEmpty(expectFinishDateTv.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择预计完成时间。");
            return false;
        }

        //【常熟项目】不需要
        /**
         * 预计整改金额
         */
//        if (StringUtils.isEmpty(expectMoneyEt.getText().toString().trim())) {
//
//            mHUDUtil.showErrorTip("请填写预计整改金额。");
//            return false;
//
//        } else {
//
//            String str = expectMoneyEt.getText().toString().trim();
//
//            Pattern r = Pattern.compile(SafeCloudConstants.MONEY_INPUT_REGULAR_EXPRESSION);
//            Matcher m = r.matcher(str);
//
//            if (m.matches()) {
//                //return true;
//            } else {
//                mHUDUtil.showErrorTip("输入的预计整改金额超过最大值。");
//                return false;
//            }
//
//        }
        //【常熟项目】不需要

        return true;
    }


    /**
     * 预计完成日期
     */
    private void pickFinishDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                Calendar calendar = Calendar.getInstance();
                Calendar now = Calendar.getInstance();
                now.setTime(calendar.getTime());

                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat dateFormat = new SimpleDateFormat(TimeFormatConstants.FORMAT_DATE, Locale.getDefault());
                String dateStr = dateFormat.format(calendar.getTime());

                if (now.after(calendar)) {
                    mHUDUtil.showErrorTip("预计完成时间不能早于当前时间。");
                    return;
                }
                expectFinishDateTv.setText(CommonUtil.avoidNullString(dateStr));

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), Constants.DIALOG_TAG_CHECK_DATE);
    }

    /**
     * 通过企业选择人员
     */
    private void showPersonList() {
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstants.KEY_TAG, SafePatrolCheckItemDetailActivity.class.getName());
        bundle.putString(KeyConstants.KEY_COMPANY_ID, company_id);
        UIHelper.showActivity(SafePatrolCheckItemDetailActivity.this, bundle, PersonListActivity.class);
    }

    /**
     * 选择复查人员
     */
    private void showReviewPersonList() {
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstants.KEY_TAG, SafePatrolCheckItemDetailActivity.class.getName());
        bundle.putString(KeyConstants.KEY_COMPANY_ID, company_id);
        UIHelper.showActivity(SafePatrolCheckItemDetailActivity.this, bundle, GovGridLeaderListActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPersonEvent(PersonEvent event) {

        if (SafePatrolCheckItemDetailActivity.class.getName().equals(event.getTag())) {
            if (GovGridLeaderListActivity.class.getName().equals(event.getFlag())) {
                reviewPersonVo = event.getPersonVo();
                reviewPersonTv.setText(CommonUtil.avoidNullString(reviewPersonVo.getUser_name()));
            } else {
                personVo = event.getPersonVo();
                responsibleTv.setText(CommonUtil.avoidNullString(personVo.getUser_name()));
            }

        }
    }

    /**
     * Dialog
     */
    private MaterialDialog materialDialog;

    private void showDialog(String remark) {
        materialDialog = new MaterialDialog.Builder(this)
                .title("提示")
                .content(remark)
                .contentColor(Color.parseColor("#FFFF0000"))
                .positiveText("确认")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                    }
                })
                .negativeText("已创建隐患")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finishActivity();
                    }
                })
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {

        if (materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelDialog();
    }

}
